package com.saku.uiprojecttest.schema;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.util.Log;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * User: Missa
 * Date: 2016-12-14
 * Time: 12:14
 * Description:
 */
public class LMRouterManager {

    private static Context mCtx;
    private static IRouter mRouter;

    public static void init(Context ctx) {
        mCtx = ctx;
        mRouter = create(IRouter.class);
    }

    public static IRouter getRouter() {
        return mRouter;
    }

    private static IRouter create(Class<?> clazz) {
        return (IRouter) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                StringBuilder sb = new StringBuilder();
                RouterUri routerUri = method.getAnnotation(RouterUri.class);
                String url = routerUri.url();
                sb.append(url);

                Annotation[][] pAnnotations = method.getParameterAnnotations();
                for (int i = 0; i < pAnnotations.length; i++) {
                    Annotation[] annotation = pAnnotations[i];
                    RouterParam anno1 = (RouterParam) annotation[0];

                    if (i == 0) {
                        sb.append("?");
                    } else {
                        sb.append("&");
                    }
                    sb.append(anno1.value());
                    sb.append("=");
                    sb.append(args[i]);
                }
                Log.d("lm", "LMRouterManager: scheme: " + sb.toString());
                openActivity(sb.toString());
                return null;
            }
        });
    }

    private static void openActivity(String uri) {
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
        i.addCategory(Intent.CATEGORY_DEFAULT);
//        i.addCategory(Intent.CATEGORY_BROWSABLE);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PackageManager pm = mCtx.getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(i, 0);
        if (resolveInfos != null &&!resolveInfos.isEmpty()) {
            mCtx.startActivity(i);
        }
//        Log.d("lm", "LMRouterManager: " + i.resolveActivity(pm));
//        if (null != i.resolveActivity(pm)){
//            mCtx.startActivity(i);
//        }
    }
}
